import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { FormArray, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'ne-registration',
  templateUrl: './registration.component.html',
  styleUrls: ['./registration.component.scss']
})
export class RegistrationComponent implements OnInit {
  public registrationFormGroup: FormGroup;
  private formArray: FormArray = new FormArray([]);

  @Input() registrationFormTitle: string = "";
  @Output() onRegistrationData: EventEmitter<any> = new EventEmitter();

  constructor(
    private formBuilder: FormBuilder,
  ) {
         /*
    email,
    firstName,
    lastName,
    password
    */
    this.registrationFormGroup = this.formBuilder.group({
      email: ["",[Validators.email, Validators.required]],
      firstName: ["", [Validators.required]],
      lastName: ["", [Validators.required]],
      password: ["", [Validators.required, Validators.maxLength(16), Validators.minLength(8)]],
      alternativeEmails: this.generateAlternativeControls(this.formBuilder)
    });
   }

  ngOnInit(): void {
  }

  generateAlternativeControls (formBuilder: FormBuilder): FormArray {
    return this.formArray;
  }

  addAlternativeEmails() {
    this.formArray.controls.length < 3 ? this.formArray.push(new FormControl("",[Validators.email, Validators.required])): null;
  }

  get alternativeEmails() {
    return this.registrationFormGroup.get('alternativeEmails') as FormArray
  }

  getalternativeEmail(index: any) {
    return this.formArray.controls[index] as FormControl;
  }

  registerMe() {
    const {value} = this.registrationFormGroup;
    this.onRegistrationData.emit(value);
  }

}
